package com.ruoyi.process.dynamic.controller;

import com.ruoyi.common.constant.PageConstants;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.entity.APIRequest;
import com.ruoyi.common.entity.APIResult;
import com.ruoyi.common.enums.StateEnum;
import com.ruoyi.common.utils.BeanUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.process.dynamic.service.BpmnDynamicService;
import com.ruoyi.process.pipemaintainence.provider.BpmnBusinessProvider;
import com.ruoyi.process.pipemaintainence.service.BpmnApprovalService;
import com.ruoyi.process.pipemaintainence.service.IDrainagePipeMainService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Api(value = "表单流程管理器", tags = "表单流程管理器")
@Controller
@RequestMapping(value = "/bpmn/form/dynamic")
public class BpmnDynamicController {

    public static final Logger logger = LoggerFactory.getLogger(BpmnDynamicController.class);
    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected IDrainagePipeMainService drainagePipeMainService;
    @Autowired
    protected ISysUserService userService;
    @Autowired
    protected BpmnApprovalService bpmnApprovalService;
    @Autowired
    protected BpmnBusinessProvider bpmnBusinessProvider;

    @Autowired
    protected BpmnDynamicService bpmnDynamicService;

    /**
     * 读取所有的流程列表
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "读取所有的流程列表", notes = "读取所有的流程列表")
    @RequestMapping(value = "/processlist", method = RequestMethod.POST)
    @ResponseBody
    public APIResult processDefinitionList(@RequestBody APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            Page<Map<String, Object>> page = bpmnDynamicService.processDefinitionList(pageNo, pageSize);
            result.setData(page);
            result.setMessage("查询流程定义列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/processlist", e);
        }
        return result;
    }


    /**
     * 获取获选人待办任务列表
     * (无区分待办和待签收)
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取获选人待办任务列表(无区分待办和待签收)", notes = "获取获选人待办任务列表(无区分待办和待签收)")
    @RequestMapping(value = "/task/todo/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult IgnoreTodoAndClaimTaskList(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            String userId = request.getParameter("userId");
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            Page<Map<String, Object>> page = bpmnDynamicService.IgnoreTodoAndClaimTaskList(pageNo, pageSize, userId);
            result.setData(page);
            result.setMessage("获取获选人待办任务列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/todo/list", e);
        }
        return result;
    }

    /**
     * 获取获选人待办任务列表
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取获选人待办任务列表(区分待办和待签收)", notes = "获取获选人待办任务列表(区分待办和待签收)")
    @RequestMapping(value = "/task/todo/list2", method = RequestMethod.POST)
    @ResponseBody
    public APIResult todoTaskList(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            String userId = request.getParameter("userId");
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            Page<Map<String, Object>> page = bpmnDynamicService.todoTaskList(pageNo, pageSize, userId);
            result.setData(page);
            result.setMessage("获取获选人待办任务列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/todo/list2", e);
        }
        return result;
    }


    /**
     * 签收任务
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation(value = "签收任务", notes = "签收任务")
    @RequestMapping(value = "/task/claim/{taskId}", method = RequestMethod.GET)
    @ResponseBody
    public APIResult claim(@PathVariable("taskId") String taskId, HttpServletRequest request) {
        APIResult result = new APIResult<>();
        try {
            String userId = request.getParameter("userId");
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            taskService.claim(taskId, userId);
            result.setMessage("签收任务成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/claim/" + taskId, e);
        }
        return result;
    }

    /**
     * 运行中的流程实例  只有权限查看自己的，如果是管理员，查看全部的运行流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "运行中的流程实例", notes = "运行中的流程实例")
    @RequestMapping(value = "/process-instance/running/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult running(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            Page<Map<String, Object>> page = bpmnDynamicService.running(pageNo, pageSize);
            result.setData(page);
            result.setMessage("查询运行中的流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/running/list", e);
        }
        return result;
    }


    /**
     * 已结束的全部流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "已结束的全部流程实例", notes = "已结束的全部流程实例")
    @RequestMapping(value = "/process-instance/finished/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult finished(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            Page<Map<String, Object>> page = bpmnDynamicService.finished(pageNo, pageSize);
            result.setData(page);
            result.setMessage("已结束的全部流程实例成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/list", e);
        }
        return result;
    }

    /**
     * 查询当前登录人的已办任务
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询当前登录人的已办任务", notes = "查询当前登录人的已办任务")
    @RequestMapping(value = "/process-instance/finished/task/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult finishedByAssignee(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            String userId = request.getParameter("userId");
            SysUser sysUser = userService.selectUserById(Long.valueOf(userId));
            if (BeanUtils.isEmpty(sysUser)) throw new RuntimeException("用户不存在");
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            Page<Map<String, Object>> page = bpmnDynamicService.finishedByAssignee(pageNo, pageSize, userId);
            result.setData(page);
            result.setMessage("查询当前登录人的已办任务成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/task/list", e);
        }
        return result;
    }


    /**
     * 查询已结束的流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询已结束的流程实例", notes = "查询已结束的流程实例")
    @RequestMapping(value = "/process-instance/findBpmnInstDetail", method = RequestMethod.POST)
    @ResponseBody
    public APIResult findBpmnInstDetail(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            Page<Map<String, Object>> page = bpmnDynamicService.findBpmnInstDetail(pageNo, pageSize);
            result.setData(page);
            result.setMessage("查询已结束的流程实例");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/list", e);
        }
        return result;
    }


    /**
     * 查询我发起的流程
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询我发起的流程", notes = "查询我发起的流程")
    @RequestMapping(value = "/process-instance/startByUserId/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult findBpmnInstByStartUserId(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            String userId = request.getParameter("userId");
            SysUser sysUser = userService.selectUserById(Long.valueOf(userId));
            if (BeanUtils.isEmpty(sysUser)) throw new RuntimeException("用户不存在");
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            Page<Map<String, Object>> page = bpmnDynamicService.findBpmnInstByStartUserId(pageNo, pageSize, userId);
            result.setData(page);
            result.setMessage("查询发起的流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/startByUserId/list", e);
        }
        return result;
    }
}
